import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "root",
      component: () => import("../views/root/index.vue"),
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../views/login/index.vue"),
    },
    {
      path: "/register",
      name: "register",
      component: () => import("../views/register/index.vue"),
    },
    {
      path: "/external",
      name: "external",
      component: () => import("../views/external/index.vue"),
    },
    {
      path: "/internal",
      name: "internal",
      component: () => import("../views/internal/index.vue"),
      redirect: "/internal/chat",
      children: [
        {
          path: "chat",
          name: "internal-chat",
          component: () => import("../views/internal/chat/index.vue"),
        },
        {
          path: "history",
          name: "internal-history",
          component: () => import("../views/internal/history/index.vue"),
        },
        {
          path: "question",
          name: "internal-question",
          component: () => import("../views/internal/question/index.vue"),
        },
        {
          path: "users",
          name: "internal-users",
          component: () => import("../views/internal/users/index.vue"),
        },
        {
          path: "config",
          name: "internal-config",
          component: () => import("../views/internal/config/index.vue"),
        },
      ],
    },
  ],
});

router.beforeEach((to, _from, next) => {
  if (to.path.startsWith("/internal")) {
    const token = localStorage.getItem("token");
    if (!token) {
      next({ name: "login" });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
